package com.ifacebox.web.common.config;

import com.ifacebox.web.common.client.OssClient;
import com.ifacebox.web.common.model.UploadProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.MultipartConfigElement;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @author znn
 */
@Configuration
public class UploadConfig {
    @Resource
    private UploadProperties uploadProperties;

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        return new MultipartConfigFactory() {
            {
                this.setLocation(uploadProperties.getLocation());
                this.setMaxFileSize(uploadProperties.getMaxFileSize());
                this.setMaxRequestSize(uploadProperties.getMaxRequestSize());
                this.setFileSizeThreshold(uploadProperties.getFileSizeThreshold());
            }
        }.createMultipartConfig();
    }

    @Bean
    public OssClient ossClient() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        return uploadProperties.getOss().getClient() == null ? new OssClient(uploadProperties) {
            @Override
            public void upload(String bucketName, String fileName) throws IOException {
            }
        } : uploadProperties.getOss().getClient()
                .getDeclaredConstructor(new Class[]{UploadProperties.class})
                .newInstance(uploadProperties);
    }
}
